﻿using Md.Api.DDD;
using Md.Api.Entity.DapperModels.MdDB;
using Md.Api.Model.Manage.MdUser.Request;
using Md.Dapper.Repositories.Md;

namespace Md.Api.Service.Manage.MdUser;
/// <summary>
/// 通过用户编号更新用户服务
/// </summary>
public class UpdateMdUserByUserIdService : ApiBase<RequestUpdateMdUserByUserIdModel>
{
    /// <summary>
    /// 用户仓储
    /// </summary>
    public MdUserRep mdUserRep { get; set; }
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        var model = new MdUserModel();

        model.UserId = Parameter.UserId;
        model.Avatar = Parameter.Avatar;
        model.UserName = Parameter.UserName;
        model.UserNick = Parameter.UserNick;
        model.UserType = Parameter.UserType;
        model.DeptId = Parameter.DeptId;
        model.RoleId = Parameter.RoleId;
        model.PostId = Parameter.PostId;
        model.Sex = Parameter.Sex;
        model.Email = Parameter.Email;
        model.Phone = Parameter.Phone;
        model.Integral = Parameter.Integral;
        model.OnLine = Parameter.OnLine;
        model.Status = Parameter.Status;
        model.Remark = Parameter.Remark;
        model.CreateBy = userKey?.ToString();
        model.CreateTime = DateTime.Now;
        model.OpenId = Parameter.OpenId;

        var user = mdUserRep.GetMdUserByUserId(model.UserId);

        if (user == null)
        {
            throw new AggregateException("用户不存在");
        }

        if (!string.IsNullOrWhiteSpace(model.UserName) && model.UserName != user.UserName)
        {
            var userNameExist = mdUserRep.CheckUserNameUnique(model.UserName);

            if (Convert.ToInt32(userNameExist) > 0)
            {
                throw new AggregateException("用户名已存在");
            }
        }

        if (!string.IsNullOrWhiteSpace(model.Email) && model.Email != user.Email)
        {
            var emailExist = mdUserRep.CheckEmailUnique(model.Email);

            if (Convert.ToInt32(emailExist) > 0)
            {
                throw new AggregateException("邮箱已存在");
            }
        }

        if (!string.IsNullOrWhiteSpace(model.Phone) && model.Phone != user.Phone)
        {
            var phoneExist = mdUserRep.CheckPhoneUnique(model.Phone);

            if (Convert.ToInt32(phoneExist) > 0)
            {
                throw new AggregateException("手机号已存在");
            }
        }

        var res = mdUserRep.UpdateMdUserByUserId(model);

        if (res > 0)
        {
            Result.Data = mdUserRep.GetMdUserByUserId(Parameter.UserId);
        }
        else
        {
            Result.Data = res;
        }
    }
}

